package com.demonzym.gtv.xml.converter;

import java.util.ArrayList;
import java.util.List;

import com.demonzym.gtv.metadata.Channel;
import com.demonzym.gtv.metadata.TvList;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class TvListConverter implements Converter {

	@Override
	public boolean canConvert(Class clazz) {
		// TODO Auto-generated method stub
		return clazz.equals(TvList.class);
	}

	@Override
	public void marshal(Object arg0, HierarchicalStreamWriter writer,
			MarshallingContext context) {
		// TODO Auto-generated method stub

	}

	@Override
	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {
		// TODO Auto-generated method stub
		TvList list = new TvList();
		reader.moveDown();//To child
		list.setTitle(reader.getAttribute("title"));
		list.setClasses(reader.getAttribute("classes"));
		list.setServer(reader.getAttribute("server"));
		reader.moveUp();//To parent
		reader.moveDown();// to next child
		List<Channel> channelList = new ArrayList<Channel>();
		while(reader.hasMoreChildren()){
			Channel c = new Channel();
			reader.moveDown();
			c.setId(Integer.parseInt(reader.getAttribute("id")));
			c.setCid(reader.getAttribute("cid"));
			c.setName(reader.getAttribute("name"));
			c.setIcon(reader.getAttribute("icon"));
			c.setEpg(reader.getAttribute("epg"));
			c.setSrc(reader.getAttribute("src"));
			c.setReplay(reader.getAttribute("replay"));
			channelList.add(c);
			reader.moveUp();
		}
		list.setChannelList(channelList);
		return list;
	}

}
